import React, { useMemo, useEffect } from 'react';
import s from './style.module.css';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import Table from '@knownsec/react-component/dist/Table';
import EmptyData from '../../../../../components/empty/EmptyData';
import Pagination from '@knownsec/react-component/dist/Pagination';
import { getParams, turnToUrlparam } from '../../../../../helpers/getUrlParams';
import cn from 'classnames';
import { Link } from 'react-router-dom';
import Button from '@kuiper-components/button';
import Input from '@kuiper-components/input';
import fetchFer from 'API/fetch';
import Select, { Option } from '@kuiper-components/select';
import { Search24 as SearchIcon } from '@carbon/icons-react';
const defaultFilter = {
	page: 1,
	limit: 10,
};
let setT = null;
function Detail({
	match: {
		params: { assetType },
	},
	checked,
	lastTid,
	jid,
	tid,
	linkType,
	atid,
}) {
	const resD = JSON.parse(sessionStorage.resD).feature;
	const [filter, setFilter] = React.useState(defaultFilter);
	const [tableData, setTableData] = React.useState({
		data: null,
		total: 0,
	});
	const [tableLoading, setTableLoading] = React.useState(false);
	const [optionData, setOptionData] = React.useState([
		{ label: '低危', value: '2' },
		{ label: '中危', value: '3' },
		{ label: '高危', value: '4' },
		{ label: '严重', value: '5' },
	]);
	const levelColor = {
		5: '#D5342F',
		4: '#F04038',
		3: '#F18246',
		2: '#FCD94A'
	}
	const colum = [
		{
			title: '漏洞名称',
			dataIndex: 'vuln_name',
			key: 'vuln_name',
		},
		{
			title: '威胁等级',
			dataIndex: 'level_name',
			key: 'level_name',
			render (e, row) {
				return <span style={row.level ? {color: levelColor[row.level]}:{}}>{e}</span>
			}
		},
		{
			title: '操作',
			dataIndex: 'name',
			key: 'name',
			render(e, row) {
				const url = linkType
					? '/asset-manage/manage/host/host-task/detail'
					: '/job-manage/host-task/vul-detail';
				return (
					<Link
						className={s.item}
						to={{
							pathname: url,
							state: { row, jid, tid: row.tid, assetType, atid },
						}}
					>
						查看详情
					</Link>
				);
			},
		},
	];
	const getData = async (num, size) => {
		setTableLoading(true);
		const sendData = { ...filter };
		sendData.job_id = jid;
		sendData.id = tid;
		const params = turnToUrlparam(sendData);
		try {
			const res = await fetchFer(
				`/api/v2/tasks/vul_host/detail/vul?${params}`,
				{
					method: 'GET',
					checkStatus: 501,
				}
			).catch(error => {
				return error;
			});
			const data = res.data.map(item => {
				item.tid = tid;
				return item;
			});
			setTableData({
				data,
				total: res.count,
			});
			setTableLoading(false);
		} catch (error) {
			setTableLoading(false);
		}
	};

	const handleChangeSearch = e => {
		e && setFilter({ ...filter, ...e });
	};
	const checkData = () => {
		let text = '暂无数据';
		let img = 'noData';
		if (!lastTid&&!tid) {
			if (!resD.hostVulTask && !resD.hostVulManualTask) {
				text = '当前套餐不支持该监测项，请先升级套餐。';
				img = 'noPrmission';
			} else if (checked === 0) {
				text = (
					<span>
						该资产未启用该监测项，您可前往“任务管理 -
						<Link
							className={s.MenuSpan}
							to={{
								pathname: '/job-manage/create-job-all',
								search: `assetType=host&jid=${jid}`,
							}}
						>
							主机安全监测
						</Link>
						”下发监测任务。
					</span>
				);
				img = 'dataLoading';
			}
		}
		return { img, text };
	};
	useEffect(() => {}, []);
	useEffect(() => {
		clearInterval(setT);
		setT = setTimeout(() => {
			getData();
		}, 500);
	}, [assetType, filter, tid]);
	return (
		<div className={s.tableMain}>
			<div className={s.search}>
				<Input
					onChange={vuln_name => {
						setFilter({ ...filter, vuln_name });
					}}
					className={s.input}
					placeholder="请输入漏洞名称"
					after={
						<SearchIcon
							className={s.icon}
							onClick={() => {
								handleChangeSearch();
							}}
						/>
					}
					value={filter.vuln_name}
					onPressEnter={() => {
						handleChangeSearch();
					}}
					type="search"
				/>
				<div className={s.selectContainer}>
					<Select
						placeholder="威胁等级"
						className={s.item}
						value={filter.level}
						allowClear={true}
						onChange={level => {
							handleChangeSearch({ level });
						}}
					>
						{optionData.reverse().map(e => (
							<Option key={e.value} value={e.value}>
								{e.label}
							</Option>
						))}
					</Select>
					<Button
						className={s.btn}
						onClick={() => {
							setFilter(defaultFilter);
						}}
					>
						重置
					</Button>
				</div>
			</div>
			<Table
				loading={tableLoading}
				className={s.newtable}
				pro
				key={Math.random().toString(36).slice(-6)}
				columns={colum}
				data={tableData.data}
				empty={
					<EmptyData
						emptyType={checkData().img}
						text={checkData().text}
						className={s.nobor}
					/>
				}
			/>
			<div>
				{/* <WarningsStatusEdit
					className={s.batchBtn}
					taskId={'ata?.task?._id'}
					isBatchSetting={true}
					afterActionSuccessful={() => setSelectedRows([])}
					idsObj={selectedRows.reduce((cur, item) => {
						cur[item.id] = item;
						return cur;
					}, {})}
				/> */}
				<div className={cn(s.df)}>
					{tableData.total > 10 && (
						<Pagination
							total={tableData.total}
							current={filter.page || 1}
							pageSize={filter.limit || 10}
							pageSizeOptions={[10, 20, 50]}
							showSizeChanger
							showQuickJumper
							showTotal={total => `共${total}条`}
							onChange={(page, limit) => {
								handleChangeSearch({ page, limit });
							}}
						/>
					)}
				</div>
			</div>
		</div>
	);
}
Detail.propTypes = {
	tid: PropTypes.any,
	atid: PropTypes.any,
	match: PropTypes.shape({
		params: PropTypes.shape({
			assetType: PropTypes.string.isRequired,
			jid: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
};
export default withRouter(Detail);
